# -*- coding: utf-8 -*-
"""
    core.db.api
    ~~~~~~~~~~~

    DB(MySQL) API.

    :copyright: (c) 2015 by Yu Jianjian
    :license: iqiyi.com
"""

from . import proxy


__all__ = ['get', 'mod', 'add', 'remove', 'join', 'sql']


def request(method, url, **kwargs):
    """ universal request.
    """

    return proxy.request(method=method, url=url, **kwargs)


def sql(sql_statement):
    """ Execute a RAW SQL statement.

    TODO: the statement here is not guarantee to be safe.

    sql('SELECT * FROM log;')
    => SELECT * FROM log;
    """

    return proxy.request('sql', url=sql_statement)


def get(url, **filters):
    """ Get record(s).

    get('log')
    => SELECT * FROM task_module_log;

    get('log', where={'id': 1122})
    => SELECT * FROM log WHERE id=1122;

    get('log', where={'id': 222, 'name': 'foo'}, which=('id', 'name'))
    => SELECT id, name FROM log WHERE id=2222 AND name="foo";

    get('task', where={'id': 111, 'name': 'bar'}, where_grouping='OR')
    => SELECT * FROM task WHERE id=111 OR name='bar';
    """
    filters.setdefault('which', '*')
    filters.setdefault('where', None)
    filters.setdefault('where_grouping', 'AND')

    return request('get', url, **filters)


def one(url, **filters):
    filters.setdefault('which', '*')
    filters.setdefault('where', None)
    filters.setdefault('where_grouping', 'AND')
    return request('one', url, **filters)


def mod(url, values, where, **filters):
    """ Modify record(s).

    mod('log', values={'finish': 2}, where={'id': 222})
    => UPDATE log SET finish=2 WHERE id=222;
    """

    filters.setdefault('where_grouping', 'AND')

    return request('mod', url, values=values, where=where, **filters)


def add(url, values, **kwargs):
    """ Add a new record.

    add('log', values={'name': 'foo', 'age': 23})
    => INSERT INTO log('name', 'age') VALUES('foo', 23);
    """

    return request('add', url, values=values, **kwargs)


def remove(url, where, **kwargs):
    """ Remove a record.

    remove('foo', where={'id': 1122})
    => DELETE FROM foo WHERE id=1122;
    """

    kwargs.setdefault('where_grouping', 'AND')

    return request('remove', url, where=where, **kwargs)


def join(urls, **filters):
    """ Generate a Joined SQL statement.
    """

    filters.setdefault('which', '*')
    filters.setdefault('where', None)
    filters.setdefault('where_grouping', 'AND')

    return request('join', urls, **filters)
